package fragment;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Hashtable;
import java.util.List;

import com.easemob.EMConnectionListener;
import com.easemob.EMEventListener;
import com.easemob.EMNotifierEvent;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMConversation;
import com.easemob.chat.EMMessage;
import com.easemob.util.EasyUtils;
import com.qzhy.female.R;

import Constant.Constance;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.util.Pair;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import app.BaseApp;

/**
 * A simple {@link Fragment} subclass.
 *
 */
public class ChatFragment extends Fragment implements OnItemClickListener , EMEventListener{

	    private ListView listView;
	    private adapter.ChatAllHistoryAdapter adapter;
	    private AlertDialog.Builder conflictBuilder;
	    // 账号在别处登录
	    public boolean isConflict = false;
	    private List<EMConversation> conversationList = new ArrayList<EMConversation>();
	    private MyConnectionListener connectionListener;
	public ChatFragment() {
		// Required empty public constructor
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View layout=inflater.inflate(R.layout.fragment_chat, null);
		InitUI(layout);
		InitDate();
		initAction();
		registerForContextMenu(listView);
		return layout;
	}
	private void initAction() {
        adapter = new adapter.ChatAllHistoryAdapter(getActivity(), 1, conversationList);
        // 设置adapter
        listView.setAdapter(adapter);
    }

	private void InitDate() {
		conversationList.addAll(loadConversationsWithRecentChat());
	}

	 /**
     * 获取所有会话
     *
     * @return
     */
    private List<EMConversation> loadConversationsWithRecentChat() {
        // 获取所有会话，包括陌生人
        Hashtable<String, EMConversation> conversations = EMChatManager.getInstance().getAllConversations();
        // 过滤掉messages size为0的conversation
        /**
         * 如果在排序过程中有新消息收到，lastMsgTime会发生变化
         * 影响排序过程，Collection.sort会产生异常
         * 保证Conversation在Sort过程中最后一条消息的时间不变
         * 避免并发问题
         */
        List<Pair<Long, EMConversation>> sortList = new ArrayList<Pair<Long, EMConversation>>();
        synchronized (conversations) {
            for (EMConversation conversation : conversations.values()) {
                if (conversation.getAllMessages().size() != 0) {
                    //if(conversation.getType() != EMConversationType.ChatRoom){
                    sortList.add(new Pair<Long, EMConversation>(conversation.getLastMessage().getMsgTime(), conversation));
                    //}
                }
            }
        }
        try {
            // Internal is TimSort algorithm, has bug
            sortConversationByLastChatTime(sortList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        List<EMConversation> list = new ArrayList<EMConversation>();
        for (Pair<Long, EMConversation> sortItem : sortList) {
            list.add(sortItem.second);
        }
        return list;
    }
    /**
     * 根据最后一条消息的时间排序
     *
     * @param conversationList
     */
    private void sortConversationByLastChatTime(List<Pair<Long, EMConversation>> conversationList) {
        Collections.sort(conversationList, new Comparator<Pair<Long, EMConversation>>() {
            @Override
            public int compare(final Pair<Long, EMConversation> con1, final Pair<Long, EMConversation> con2) {

                if (con1.first == con2.first) {
                    return 0;
                } else if (con2.first > con1.first) {
                    return 1;
                } else {
                    return -1;
                }
            }

        });
    }
	private void InitUI(View layout) {
		listView = (ListView) layout.findViewById(R.id.list);
		 listView.setOnItemClickListener(this);
	}
	
	/**
     * 监听链接状态
     */
    public class MyConnectionListener implements EMConnectionListener {

        @Override
        public void onConnected() {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
//                    errorItem.setVisibility(View.GONE);
                }
            });

        }
        @Override
        public void onDisconnected(final int error) {
            final String st1 = getResources().getString(R.string.can_not_connect_chat_server_connection);
            final String st2 = getResources().getString(R.string.the_current_network);
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                	Toast.makeText(getContext(), "无法连接", 1).show();
                }
            });
        }
    }
	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		EMConversation conversation = adapter.getItem(position);
        String username = conversation.getUserName();
        String st2 = getResources().getString(R.string.Cant_chat_with_yourself);
        if (username.equals(BaseApp.getUserName())) {
        	Toast.makeText(getContext(), st2, 1).show();
        } else {
            Intent intent = new Intent(getContext(), activity.ChatActivity.class);
            intent.putExtra(Constance.CHATS.CHATTYPE, activity.ChatActivity.CHATTYPE_SINGLE);//单聊
            intent.putExtra(Constance.CHATS.USERID, username);
            startActivity(intent);
        }
	}

	@Override
	public void onEvent(EMNotifierEvent event) {
		 switch (event.getEvent()) {
         case EventNewMessage: // 普通消息
         {
             final EMMessage message = (EMMessage) event.getData();
             if (!EasyUtils.isAppRunningForeground(getActivity())) {
                 //后台运行，发通知提示
                 app.HXSDKHelper.getInstance().getNotifier().onNewMsg(message);
                 getActivity().runOnUiThread(new Runnable() {
					@Override
					public void run() {
						 utils.JgUtil.showLocalNotification(getActivity(), 1, "有人给你发私信了",
		                		 message.toString(), 111111,
		    					java.lang.System.currentTimeMillis() + 10); 
					}
				});  
              } else {
                 refreshUI();
             }
             break;
         }
         case EventOfflineMessage: {
             if (EasyUtils.isAppRunningForeground(getActivity())) {
                 refreshUI();
             }

             break;
         }
         case EventConversationListChanged: {
             if (EasyUtils.isAppRunningForeground(getActivity())) {
                 refreshUI();
             }
             break;
         }
         default:
             break;
     }
	}

    /**
     * 刷新界面
     */
    private void refreshUI() {
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                conversationList.clear();
                conversationList.addAll(loadConversationsWithRecentChat());
                if (adapter != null)
                    adapter.notifyDataSetChanged();
                
            }
        });
    }
    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        getActivity().getMenuInflater().inflate(R.menu.delete_message, menu);
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        boolean handled = false;
        boolean deleteMessage = false;
        if (item.getItemId() == R.id.delete_message) {
            deleteMessage = true;
            handled = true;
        } else if (item.getItemId() == R.id.delete_conversation) {
            deleteMessage = false;
            handled = true;
        } else if (item.getItemId() == R.id.cancel) {
            deleteMessage = false;
            handled = false;
        }
        if (handled) {
            EMConversation tobeDeleteCons = adapter.getItem(((AdapterView.AdapterContextMenuInfo) item.getMenuInfo()).position);
            // 删除此会话
            EMChatManager.getInstance().deleteConversation(tobeDeleteCons.getUserName(), tobeDeleteCons.isGroup(), deleteMessage);
            adapter.remove(tobeDeleteCons);
            adapter.notifyDataSetChanged();
        }
        return handled ? true : super.onContextItemSelected(item);
    }
    @Override
	public void onResume() {
        super.onResume();
        connectionListener = new MyConnectionListener();
        EMChatManager.getInstance().addConnectionListener(connectionListener);
        EMChatManager.getInstance().registerEventListener(this,
                new EMNotifierEvent.Event[]{EMNotifierEvent.Event.EventNewMessage, EMNotifierEvent.Event.EventOfflineMessage, EMNotifierEvent.Event.EventConversationListChanged});
        refreshUI();
    }

    @Override
	public void onStop() {
        super.onStop();
        if (EasyUtils.isAppRunningForeground(getActivity())) {//如果前台运行，取消监听
            EMChatManager.getInstance().unregisterEventListener(this);//取消监听
        }

    }

    @Override
	public void onDestroy() {
        super.onDestroy();

        if (conflictBuilder != null) {
            conflictBuilder.create().dismiss();
            conflictBuilder = null;
        }
        if (connectionListener != null) {
            EMChatManager.getInstance().removeConnectionListener(connectionListener);
        }
        EMChatManager.getInstance().unregisterEventListener(this);//取消监听
        EmchatLogOut();
        Log.d("ddfadasf", "1111");
    }
    /**
     * 环信退出登录
     */

    private void EmchatLogOut() {
    	Toast.makeText(getContext(), "退出环信", 1).show();
    }
}
